<?php
/**
 * YGdImagine.php
 *
 * @author Hua Yang <htmlcook@gmail.com>
 * @since 2.0
 */

Yii::import('common.components.image.YImagineInterface');
Yii::import('common.components.image.gd.YGdImage');

/**
 * Class GdImagine
 */
class YGdImagine implements YImagineInterface
{
	public function __construct()
	{
		if (!function_exists('gd_info')) {
			throw new RuntimeException('Gd not installed');
		}

		if (version_compare(GD_VERSION, '2.0.1', '<')) {
			throw new RuntimeException('GD2 version 2.0.1 or higher is required');
		}

		$this->info = gd_info();
	}

	/**
	 * @param $path
	 * @return YGdImage
	 * @throws RuntimeException
	 * @throws InvalidArgumentException
	 */
	public function open($path)
	{
		$handle = @fopen($path, 'r');
		if (false === $handle) {
			throw new InvalidArgumentException(sprintf(
				'File %s doesn\'t exist', $path
			));
		}

		try {
			$image = $this->read($handle);
		} catch (Exception $e) {
			fclose($handle);
			throw new RuntimeException(sprintf('Unable to open image %s', $path), $e->getCode(), $e);
		}

		return $image;
	}

	public function load($string)
	{
		$resource = @imagecreatefromstring($string);

		if (!is_resource($resource)) {
			throw new InvalidArgumentException('An image could not be created from the give input');
		}

		return $this->wrap($resource);
	}

	public function read($resource)
	{
		if (!is_resource($resource)) {
			throw new InvalidArgumentException('Variable does not contain a stream resource');
		}

		$content = stream_get_contents($resource);

		if (false === $content) {
			throw new InvalidArgumentException('Cannot read resource content');
		}

		return $this->load($content);
	}

	private function wrap($resource)
	{
		if (!imageistruecolor($resource)) {
			list($width, $height) = array(imagesx($resource), imagesy($resource));

			$truecolor = imagecreatetruecolor($width, $height);
			$transparent = imagecolorallocatealpha($truecolor, 255, 255, 255, 127);

			imagefill($truecolor, 0, 0, $transparent);

			imagecopymerge($truecolor, $resource, 0, 0, 0, 0, $width, $height, 100);

			imagedestroy($resource);
			$resource = $truecolor;
		}

		if (false === imagealphablending($resource, false) ||
			false === imagesavealpha($resource, true)
		) {
			throw new RuntimeException(
				'Could not set alphableding, savealpha and antialias values'
			);
		}

		if (function_exists('imageantialias')) {
			imageantialias($resource, true);
		}

		return new YGdImage($resource);
	}
}